<template>
  <div class="sign-contract-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="header-title">签订合同 - {{ project.projectName }}</span>
        <el-tag :type="getStatusTagType(project.status)" size="small">
          {{ project.status }}
        </el-tag>
      </template>
    </el-page-header>

    <el-card class="contract-form-card">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 合同基本信息 -->
        <el-divider content-position="left">合同基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="form.contractCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" class="w-full">
                <el-option label="租赁合同" value="lease" />
                <el-option label="合作协议" value="cooperation" />
                <el-option label="投资协议" value="investment" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker
                  v-model="form.signDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择签约日期"
                  class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="amount">
              <el-input-number
                  v-model="form.amount"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  class="w-full"
              >
                <template #append>万元</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 合同条款 -->
        <el-divider content-position="left">合同条款</el-divider>
        <el-form-item label="合同内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              :rows="6"
              placeholder="请输入合同主要内容..."
              show-word-limit
              maxlength="2000"
          />
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item label="合同附件" >
          <el-upload
              action='${import.meta.env.VITE_API_BASE_URL}/api/upload'
              :headers="{ Authorization: `Bearer ${token}` }"
              :before-upload="checkFile"
              name="files"
              multiple
              :limit="3"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemove"
              list-type="text"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">支持多种格式，单个文件不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

const route = useRoute()
const router = useRouter()

const formRef = ref(null)

// 项目数据
const project = ref({})

// 表单数据
const form = ref({
  contractCode: '',
  contractType: 'lease',
  signDate: '',
  amount: 0,
  content: '',
  attachments: []
})

// 表单验证规则
const rules = {
  contractCode: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  contractType: [ // 新增合同类型验证
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  signDate: [
    { required: true, message: '请选择签约日期', trigger: 'change' }
  ],
  amount: [ // 新增金额验证
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value <= 0) {
          callback(new Error('合同金额必须大于零'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  content: [
    { required: true, message: '请输入合同内容', trigger: 'blur' }
  ]
}

// 加载项目数据
const loadProject = async () => {
  const { data } = await api.get(`/api/projects/${route.query.id}`)
  console.log('后端返回：', data)
  project.value = data
}


onMounted(async () => {
  await loadProject()
  
})

const checkFile = (file) => {
  // 允许的文件类型
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'text/plain',
    'image/jpeg',
    'image/png',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ];

  // 验证类型
  const isAllowedType = allowedTypes.includes(file.type);
  // 验证大小（15MB）
  const isLt15M = file.size / 1024 / 1024 < 15;

  if (!isAllowedType) {
    ElMessage.error('仅支持PDF/DOC/TXT/JPG/PNG文件');
    return false;
  }
  if (!isLt15M) {
    ElMessage.error('文件大小不能超过15MB');
    return false;
  }
  return true;
};

// 文件上传成功处理
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.value.attachments = response.data // 更新文件列表
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleRemove = () => {
  // 文件删除时也触发验证
  formRef.value.validateField('attachments')
}

// 提交表单
const submitForm = async () => {
  try {
    // 1. 校验
    await formRef.value.validate()

    // 2. 用户确认
    await ElMessageBox.confirm(
      `确定要签订项目“${project.value.projectName}”的合同吗？`,
      '请确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )

    // 3. 组装数据
    const payload = {
      contractCode: form.value.contractCode.trim(),
      contractType: form.value.contractType,
      signDate: form.value.signDate,
      contractAmount: form.value.amount,   // 后端字段叫 contractAmount
      contractContent: form.value.content.trim(),
      attachments: form.value.attachments  // 目前只是 URL 数组
    }

    // 4. 先存合同
    await api.post(`/api/projects/${project.value.id}/contracts`, payload)

    // 5. 再标为已签约
    await api.post(`/api/projects/${project.value.id}/sign`)

    ElMessage.success('合同签订成功')
    router.push({ name: 'negotiating' })   // 跳转到“在谈项目”列表页
  } catch (e) {
    // 用户点“取消”不算错误
    if (e === 'cancel') return
    // 真正的异常
    console.error(e)
    ElMessage.error(e.response?.data?.message || '提交失败，请重试')
  } finally {
    // 恢复按钮
    if (submitBtn) submitBtn.disabled = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 状态标签类型
const getStatusTagType = (status) => {
  const map = {
    '进行中': 'success',
    '已签约': '',
    '已完成': 'info'
  }
  return map[status] || ''
}
</script>

<style scoped>
.sign-contract-container {
  padding: 20px;
}

.header-title {
  margin-right: 10px;
  font-size: 18px;
}

.contract-form-card {
  margin-top: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
}
</style>